# -*- coding: utf-8 -*-
import json
import subprocess
from Common.mysql import redis_client
from src.ApiTest.ApiInfo.Database.api_database import ApiInfo, ApiInfoSchema
from src.ApiTest.SqlData.Database.sql_database import SqlData, SqlSchema
from src.ApiTest.ProjectConfig.Database.mysqlConfig_database import MysqlConfig, MysqlConfigSchema
from src.ApiTest.Core.operational_sql import OperationalSql
from src.TestApiRun.api_run import ApiRun

class RunCase:
    """
    运行接口测试用例
    """
    def run_case(self, case_name, project_id, request_info, environment, user_id):

        # 根据用例信息，拆分接口信息或SQL信息
        responses_data = {}
        api_info = json.loads(request_info)
        for api in api_info:
            if api['requestType'] == 'API':
                # 执行接口请求
                api_id = api['requestData'].split('/')[1]
                data = ApiInfo.query.filter_by(id=api_id).first()
                api_schema = ApiInfoSchema()
                api_data = api_schema.dump(data)
                api_name = api_data['apiName']

                api_data['user_id'] =user_id
                api_data['caseName'] = case_name
                api_data['environment'] = environment

                # 将 api_data 转换为 JSON 字符串
                case_data_json = json.dumps(api_data)

                # 调用 pytest 命令执行测试
                result = subprocess.run(
                    [
                        'pytest',
                        'src/TestApiRun/api_run_test.py',
                        '--alluredir=allure-results',
                        f'--case_data={case_data_json}',
                        '-s'
                    ],
                    capture_output=True,
                    text=True
                )

                # response = ApiRun().api_request(environment, api_data, user_id)
                responses_data[api_name] = result
            elif api['requestType'] == 'SQL':
                # 执行SQL操作
                sql_id = api['requestData'].split('/')[1]
                # 查询SQL基础信息
                sql_data = SqlData.query.filter_by(id=sql_id).first()
                sql_data_schema = SqlSchema()
                sql_info = sql_data_schema.dump(sql_data)
                db_type = sql_info['databaseType']
                func = sql_info['functionName'].split('[')[0]
                sql = eval(sql_info['sqlData'])
                sql_name = sql_info['configName']
                # 查询db_info
                db_data = MysqlConfig.query.filter_by(projectId=project_id, databaseType=db_type, environment=environment).first()
                db_schema = MysqlConfigSchema()
                db_info = db_schema.dump(db_data)
                # 执行SQL
                sql_result = OperationalSql().operational_sql(db_info, func, sql)
                responses_data[sql_name] = sql_result

        # 调用接口运行方法，执行接口或SQL
        return responses_data
